package com.remoter.transport.socket.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.remoter.basic.bean.support.RemoterRequest;
import com.remoter.basic.bean.support.RemoterResponse;
import com.remoter.basic.provider.IProvider;
import com.remoter.basic.task.ITask;
import com.remoter.basic.task.ITaskCallBack;
import com.remoter.transport.socket.server.task.SocketMessageTask;
import com.remoter.transport.socket.server.task.SocketMessageTaskCallBack;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author			koko
 * @date 			2017-08-09 09:27:46
 * @description 	类功能说明
 */
public class ServerMessageHandler extends ChannelInboundHandlerAdapter{
	
	private static final Logger logger = LoggerFactory.getLogger(ServerMessageHandler.class);
	
	private IProvider provider;
	public ServerMessageHandler(IProvider provider){
		this.provider = provider;
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
		if(null != msg && msg instanceof RemoterRequest){
			logger.debug("get request data :" + msg);
			RemoterRequest remoterRequest = (RemoterRequest)msg;
			RemoterResponse remoterResponse = new RemoterResponse(remoterRequest.getToken());
			ITask messageTask = new SocketMessageTask(remoterRequest,remoterResponse);
			ITaskCallBack messageTaskCallBack = new SocketMessageTaskCallBack(remoterRequest,remoterResponse,ctx);
			this.provider.submit(messageTask,messageTaskCallBack);
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
		ctx.close();
	}
	
}